/**
 * weapp-js
 * https://code.aliyun.com/jionglee/weapp_base.git
 * Copyright@ 2020 Motigo, Inc.
 * 
 */
import base_request from './base_request.js';
import session from './session.js';

export default {    
    chooseImage(opts) {
        return new Promise((resolve, reject) => {
            wx.chooseImage({
                count: opts.count || 9, // 默认为9
                sizeType: opts.sizeType || ['compressed'], // 指定原图或者压缩图
                sourceType: opts.sourceType || ['album'], // 指定图片来源
                success: res => {
                    var tempFilePaths = res.tempFilePaths;
                    let results = [];

                    if (opts.upload === false) { // 强制不上传，默认自动上传
                        tempFilePaths.forEach(item => {
                            results.push({
                                local_file: item
                            });
                        });
                        resolve(results);
                    } else {
                        opts.showProgress && this._showUploadingProgress(tempFilePaths.length, 0, 0);
                        let chainedPromise = tempFilePaths.reduce((pre, path) => {
                            return pre.then(() => {
                                return this.uploadFile({
                                    filePath: path,
                                    progress: (progress) => {
                                        opts.showProgress && this._showUploadingProgress(tempFilePaths.length, results.length, progress);
                                    }
                                }).then(data => {
                                    data.local_file = path;
                                    results.push(data);
                                }, err => {
                                    console.error('upload fail:', err);
                                });
                            });
                        }, Promise.resolve(results));

                        chainedPromise.then(() => {
                            opts.showProgress && wx.hideLoading();
                            resolve(results)
                        }, () => {
                            opts.showProgress && wx.hideLoading();
                            reject();
                        });
                    }
                },
                fail: () => {
                    reject();
                }
            });
        });
    },
    uploadFile(opts) {
        return new Promise((resolve, reject) => {
            let task = wx.uploadFile({
                url: base_request.HOST + '/file/' + session.appid,
                filePath: opts.filePath,
                name: 'file',
                formData: {
                    'openid': session.user.openid
                },
                success: res=>{
                    if (res.statusCode < 400) {
                        let pkg = JSON.parse(res.data);
                        if (pkg.ret == 0) {
                            this._checkUploadResult(pkg.data.sec_task_id).then( ()=>{
                                resolve(pkg.data);
                            }, err=>{
                                console.error('check file result fail! err:', err);
                                reject({
                                    ret: -3,
                                    msg: 'file secure check fail!'
                                })
                            });
                        } else {
                            reject({
                                ret: pkg.ret,
                                msg: pkg.msg
                            })
                        }
                    } else {
                        reject({
                            ret: -2,
                            msg: 'upload fail, status code:' + res.statusCode
                        });
                    }
                },
                fail: err => {
                    reject({
                        ret: -3,
                        msg: err
                    });
                }
            });

            task.onProgressUpdate((res) => {
                opts.progress && opts.progress(res.progress);
            })
        });
    },
    uploadFiles(opts) {
        return new Promise((resolve, reject) => {
            let results = {};
            let chainedPromise = opts.files.reduce((pre, path) => {
                return pre.then(() => {
                    return this.uploadFile({
                        filePath: path
                    }).then(data => {
                        data.ret = 0;
                        results[path] = data;
                        opts.progress && opts.progress({
                            current: {
                                local_file: path,
                                success: true
                            },
                            total: results
                        })
                    }, err => {
                        console.error('upload fail:', err);
                        results[path] = err;
                        opts.progress && opts.progress({
                            current: {
                                local_file: path,
                                success: false
                            },
                            total: results
                        })
                    });
                });
            }, Promise.resolve(results));

            chainedPromise.then(() => {
                resolve(results)
            }, () => {
                reject();
            });
        });
    },
    // 显示上传进度
    _showUploadingProgress(total, finished) {
        wx.showLoading({
            title: `${finished}/${total}`
        })
    },
    _checkUploadResult(task_id, check_count=0) {        
        return new Promise( (resolve, reject)=>{
            if (check_count>=5) {
                reject('check task timeout');
            } else {
                setTimeout( ()=>{
                    base_request.get('/file_task/' + task_id).then( res=>{
                        if (res.status == 'SUCCESS') {
                            if(res.result == 'PASS') {
                                resolve();
                            } else {
                                reject(res);
                            }
                        } else {
                            this._checkUploadResult(task_id, ++check_count).then(resolve, reject);
                        }                        
                    }, err=>{
                        console.error('check file task fail, err:', err);
                        this._checkUploadResult(task_id, ++check_count).then(resolve, reject);
                    });
                }, 500 + check_count*500);
            }
        });        
    }
}